package cn.com.wxd.service.user;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.biz.user.UsersService;
import cn.com.wxd.biz.user.UsersServiceImpl;
import cn.com.wxd.entity.user.AccountInfo;
import cn.com.wxd.entity.user.UsersInfo;
import cn.com.wxd.util.SpringContextHolder;

/**
 * Title:
 * Description:
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2017
 * All right reserved.
 * Created by WangXuDong on 2017/6/8.
 *
 * @author WangXuDong
 * @version 1.0
 */
public class UserCore {

    private static final Logger log = LoggerFactory.getLogger(UserCore.class);

    /**
     * 获取当前session登录的账户
     * @param session
     * @return
     */
    public AccountInfo getLoginAccount(HttpSession session) {
        Object o = session.getAttribute("LOGINACCOUNTINFO");
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {  //shiro授权中有用户
            if (o == null) { //session中没有。
                UsersService us = SpringContextHolder.getBean("usersService", UsersServiceImpl.class);
                String userName = (String) subject.getPrincipal();
                AccountInfo accountInfo = us.queryAccount(userName);
                session.setAttribute("LOGINACCOUNTINFO", accountInfo);
                return accountInfo;
            } else {
                return (AccountInfo) o;
            }
        } else if (subject.isRemembered()) {
            UsersService us = SpringContextHolder.getBean("usersService", UsersServiceImpl.class);
            String userName = (String) subject.getPrincipal();
            //这里不做登录操作，只是获取了用户信息，因此状态还是记住密码或登录状态
            AccountInfo accountInfo = us.queryAccount(userName);
            UsersInfo ui = null;
            if (accountInfo != null) {
                ui = accountInfo.getUsersInfo();
            }
            if (ui != null && ui.getIsDisabled().equalsIgnoreCase("Y")) {
                //登出用户，因为该用户的所有账号都禁用了。
                logoutUser(session);
                return null;
            }
            // 登录当前账号
            session.setAttribute("LOGINACCOUNTINFO", ui);
            return accountInfo;
        } else {
            //登出用户，因为在shiro中已经没有登录信息了
            logoutUser(session);
        }
        return null;
    }

    /**
     * 添加登录用户信息
     * @param session
     * @param accountInfo
     * @param isRememberPwd 是否记住密码
     * @return
     */
    public AccountInfo setLoginUser(HttpSession session, AccountInfo accountInfo
            , boolean isRememberPwd) {
        if (accountInfo != null) {
            try {
                UsersInfo usersInfo = accountInfo.getUsersInfo();
                Subject subject = SecurityUtils.getSubject();
                if (subject.isAuthenticated()) {//如果用户是登录状态，那么就登更新session
                    session.removeAttribute("LOGINACCOUNTINFO");
                    session.setAttribute("LOGINACCOUNTINFO", accountInfo);
                }
                UsernamePasswordToken token = new UsernamePasswordToken(accountInfo.getUserName()
                        , usersInfo.getPassWord());
                if (usersInfo.getUserType().equalsIgnoreCase("SYSTEM")
                        || usersInfo.getUserType().equalsIgnoreCase("ADMIN")) {
                    //管理员账号或者系统账号都不会记住密码
                    token.setRememberMe(false);
                } else {
                    token.setRememberMe(isRememberPwd);
                }
                //TODO 更多的权限不会记住密码
                subject.login(token); // 登录
            } catch (AuthenticationException e) {
                log.error(e.getMessage(), e);
                return null;
            }
            return accountInfo;
        }
        return null;
    }

    /**
     * 注销当前登录的用户
     *
     * @param session
     */
    public void logoutUser(HttpSession session) {
        session.removeAttribute("LOGINACCOUNTINFO");
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated() || subject.isRemembered()) {
            subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
        }
        //request.getSession().invalidate();  //清空session
    }

}
